<template>
	<div class="list-page" :style='{}'>
        <div class="breadcrumb-wrapper" style="width: 100%;">
            <div class="bread_view">
                <el-breadcrumb separator="" class="breadcrumb">
                    <el-breadcrumb-item class="first_breadcrumb" :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item class="second_breadcrumb" v-for="(item,index) in breadList" :key="index">
                        <template v-if="isDaoshi && item.name === '项目申请'">项目指导</template>
                        <template v-else>{{item.name}}</template>
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="back_view" v-if="centerType">
                <el-button class="back_btn" @click="backClick" type="primary">返回</el-button>
            </div>
        </div>
		<el-form :inline="true" :model="searchQuery" class="list_search">
			<div class="search_view">
				<div class="search_label">
					项目名称：
				</div>
				<div class="search_box">
					<el-input class="search_inp" v-model="searchQuery.xiangmumingcheng" placeholder="项目名称"
						clearable>
					</el-input>
				</div>
			</div>
			<div class="search_view">
				<div class="search_label">
					项目分类：
				</div>
				<div class="search_box">
					<el-input class="search_inp" v-model="searchQuery.xiangmufenlei" placeholder="项目分类"
						clearable>
					</el-input>
				</div>
			</div>
			<div class="search_view">
				<div class="search_label">
					项目阶段：
				</div>
				<div class="search_box">
					<el-input class="search_inp" v-model="searchQuery.xiangmujieduan" placeholder="项目阶段"
						clearable>
					</el-input>
				</div>
			</div>
			<div class="search_btn_view">
				<el-button class="search_btn" type="primary" @click="searchClick">搜索</el-button>
				<el-button class="add_btn" type="success" v-if="btnAuth('xiangmushenqing','新增')" @click="addClick">新增</el-button>
			</div>
		</el-form>
		<div class="page_list">
			<div class="data_box">
                <div class="table_view">
					<el-table v-loading="listLoading" class="data_table" :data="list" border :row-style="{'cursor':'pointer'}"
						@row-click="tableDetailClick" :stripe='true'>
						<el-table-column :resizable='true' align="left" header-align="left" type="selection" width="55" />
						<el-table-column label="序号" width="120" :resizable='true' align="left" header-align="left">
							<template #default="scope">{{ (listQuery.page-1)*listQuery.limit+scope.$index + 1}}</template>
						</el-table-column>
						<el-table-column label="学号" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.xuehao}}
							</template>
						</el-table-column>
						<el-table-column label="学生姓名" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.xueshengxingming}}
							</template>
						</el-table-column>
						<el-table-column label="专业" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.zhuanye}}
							</template>
						</el-table-column>
						<el-table-column label="项目名称" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.xiangmumingcheng}}
							</template>
						</el-table-column>
						<el-table-column label="负责人账号" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.fuzerenzhanghao}}
							</template>
						</el-table-column>
						<el-table-column label="负责人姓名" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.fuzerenxingming}}
							</template>
						</el-table-column>
						<el-table-column label="项目阶段" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.xiangmujieduan}}
							</template>
						</el-table-column>
						<el-table-column label="申请时间" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.shenqingshijian}}
							</template>
						</el-table-column>
						<el-table-column label="指导导师" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								{{scope.row.zhidaodaoshi}}
							</template>
						</el-table-column>
						<el-table-column label="审核状态" v-if="centerType" :resizable='true' align="left" header-align="left">
							<template #default="scope">
								<el-tag type="success" v-if="scope.row.sfsh=='是'">通过</el-tag>
								<el-tag type="danger" v-if="scope.row.sfsh=='否'">未通过</el-tag>
								<el-tag type="warning" v-if="scope.row.sfsh=='待审核'">待审核</el-tag>
							</template>
						</el-table-column>
						<el-table-column v-if="isDaoshi" label="操作" width="180" align="center">
							<template #default="scope">
								<el-button type="warning" size="small" @click.stop="handleResult(scope.row)">成果</el-button>
								<el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
                </div>
				<el-pagination
					background 
					:layout="layouts.join(',')"
					:total="total" 
					:page-size="listQuery.limit"
                    v-model:current-page="listQuery.page"
					prev-text="上一页"
					next-text="下一页"
					:hide-on-single-page="false"
					:style='{}'
					@size-change="sizeChange"
					@current-change="currentChange"/>
			</div>
		</div>
		<el-dialog v-model="preViewVisible" :title="'查看大图'" width="60%" destroy-on-close>
			<img :src="preViewUrl" style="width: 100%;" alt="">
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		getCurrentInstance,
		nextTick,
        computed,
	} from 'vue';
	import {
		useRoute,
		useRouter
	} from 'vue-router';
    import {
        useStore
    } from 'vuex';
    const store = useStore()
    const user = computed(()=>store.getters['user/session'])
	const context = getCurrentInstance()?.appContext.config.globalProperties;
	const router = useRouter()
	const route = useRoute()
    // 判断是否为导师角色
    const isDaoshi = computed(() => {
        return context?.$toolUtil.storageGet("frontRole") === "导师" || route.query.role === 'daoshi';
    });
	//基础信息
	const tableName = 'xiangmushenqing'
	const formName = '项目申请'
	//基础信息
	const breadList = ref([{
		name: formName
	}])
	const list = ref([])
	const listQuery = ref({
		page: 1,
		limit: 20,
	})
	const total = ref(0)
	const listLoading = ref(false)
	//权限验证
	const btnAuth = (e,a)=>{
		if(centerType.value){
			return context?.$toolUtil.isBackAuth(e,a)
		}else{
			const role = route.query.role || ''
			if(role === 'daoshi'){
				return context?.$toolUtil.isAuth(e,a)
			}
			return false;
		}
	}
    const tableDetailClick = (row) => {
        const role = route.query.role || ''
        // 导师角色不跳转到详情页
        if (isDaoshi.value) {
            return;
        }
        router.push({
            path: '/index/xiangmushenqingDetail',
            query: {
                id: row.id,
                ...(centerType.value ? {centerType: '1'} : {}),
                role: role,
                xiangmumingcheng: row.xiangmumingcheng
            }
        })
    }
	const addClick = () => {
		router.push('/index/xiangmushenqingAdd')
	}
	//判断是否从个人中心跳转
	const centerType = ref(false)
	//返回
	const backClick = () => {
		router.push(`/index/${context?.$toolUtil.storageGet('frontSessionTable')}Center`)
	}
	//搜索
	const searchQuery = ref({})
	//下拉列表
	const searchClick = () => {
		listQuery.value.page = 1
		getList()
	}
	//分页
	const layouts = ref(["total","prev","pager","next","sizes","jumper"])
	const sizeChange = (size) => {
		listQuery.value.limit = size
		getList()
	}
	const currentChange = (page) => {
		listQuery.value.page = page
		getList()
	}
	//分页
	//列表
		const getList = () => {
			listLoading.value = true
			let params = {
				page: listQuery.value.page,
				limit: listQuery.value.limit,
				sort: 'tijiaoshijian',
				order: 'desc'
			}
			
			// 根据项目名称筛选
			if(route.query.xiangmumingcheng) {
				params['xiangmumingcheng'] = route.query.xiangmumingcheng
			} else if(searchQuery.value.xiangmumingcheng) {
				params['xiangmumingcheng'] = '%' + (searchQuery.value.xiangmumingcheng || '') + '%'
			}
			if(searchQuery.value.xiangmufenlei){
				params.xiangmufenlei = '%' + (searchQuery.value.xiangmufenlei || '') + '%'
			}
			if(searchQuery.value.xiangmujieduan){
				params.xiangmujieduan = '%' + (searchQuery.value.xiangmujieduan || '') + '%'
			}
			
			// 导师角色过滤：只显示指导且已通过审核的项目
			if (isDaoshi.value && user.value) {
				console.log("当前导师信息：", user.value);
				// 添加指导导师过滤条件 - 尝试多种方式获取用户名
				let username = '';
				
				// 尝试方式1：从user对象获取
				if (user.value.daoshigonghao) {
					username = user.value.daoshigonghao;
				} 
				// 尝试方式2：直接从存储获取
				else if (context.$toolUtil.storageGet('username')) {
					username = context.$toolUtil.storageGet('username');
				}
				// 尝试方式3：从session表获取
				else if (context.$toolUtil.storageGet('frontSessionTable') === 'daoshi' && context.$toolUtil.storageGet('frontUsername')) {
					username = context.$toolUtil.storageGet('frontUsername');
				}
				
				console.log("使用导师工号过滤：", username);
				// 只有在获取到用户名时才添加过滤条件
				if (username) {
					params['zhidaodaoshi'] = username;
					// 添加审核状态过滤条件
					params['sfsh'] = '是';
				} else {
					console.error("无法获取导师工号，请检查登录状态");
					context.$toolUtil.message('无法获取导师工号，请重新登录', 'error');
				}
			}
			
        params['sort'] = 'tijiaoshijian';
        params['order'] = 'desc';
        // 用户信息过滤条件已移除
			const apiPath = centerType.value ? `/cl29556703/${tableName}/page` : `/cl29556703/${tableName}/list`
			console.log("请求API路径：", apiPath);
			console.log("请求参数：", params);
			context?.$http({
				url: apiPath,
				method: 'get',
				params: params,
				baseURL: '/' // 使用相对路径，让代理生效
			}).then(res => {
				console.log("API响应：", res);
				listLoading.value = false
				if(res.data && res.data.data) {
					list.value = res.data.data.list || []
					total.value = Number(res.data.data.total || 0)
				} else {
					list.value = []
					total.value = 0
				}
			}).catch(err => {
				console.error("API错误：", err);
				listLoading.value = false
			})
	}
	//下载文件
	const download = (file) =>{
		if(!file){
			context?.$toolUtil.message('文件不存在','error')
		}
		const a = document.createElement('a');
		a.style.display = 'none';
		a.setAttribute('target', '_blank');
		file && a.setAttribute('download', file);
		a.href = context?.$config.url + file;
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
	}
	// 查看大图
	const preViewUrl = ref('')
	const preViewVisible = ref(false)
	const preViewClick = (url) =>{
		preViewUrl.value = url
		preViewVisible.value = true
	}
	const init = async() => {
		centerType.value = !!route.query.centerType
		try {
			// 检查用户会话
			const token = context.$toolUtil.storageGet('frontToken')
			if(!token) {
				context.$toolUtil.message('请先登录','error')
				router.push('/index/login')
				return
			}
			
			// 确保用户信息已加载
			await store.dispatch('user/getSession')
				.catch(err => {
					context.$toolUtil.message('会话获取失败，请重新登录','error')
					context.$toolUtil.storageRemove('frontToken')
					router.push('/index/login')
					return Promise.reject(err)
				})
				
			// 只有会话获取成功才继续
			getList()
		} catch (err) {
			// 静默处理初始化错误
		}
	}
	init()

    // 处理成果按钮点击
    const handleResult = (row) => {
        if (!context?.$toolUtil.storageGet('frontToken')) {
            context?.$toolUtil.message('请登录后再操作！','error')
            return false
        }

        // 存储跨表数据
        context?.$toolUtil.storageSet('crossObj', JSON.stringify(row))
        context?.$toolUtil.storageSet('crossTable', tableName)
        
        // 跳转到成果添加页面
        router.push(`/index/xiangmuchengguoAdd?type=cross&&id=${row.id}`)
    }
    
    // 处理删除按钮点击
    const handleDelete = (row) => {
        if (!context?.$toolUtil.storageGet('frontToken')) {
            context?.$toolUtil.message('请登录后再操作！','error')
            return false
        }
        
        // 显示确认对话框
        context?.$confirm(`是否删除此项目申请？`, '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }).then(() => {
            // 发送删除请求
            context?.$http({
                url: `${tableName}/delete`,
                method: 'post',
                data: [row.id]
            }).then(res => {
                context?.$toolUtil.message('删除成功', 'success')
                // 重新加载数据
                getList()
            }).catch(err => {
                console.error('删除失败:', err)
                context?.$toolUtil.message('删除失败', 'error')
            })
        }).catch(() => {
            // 取消删除
        })
    }
</script>
<style lang="scss" scoped>
	// 返回盒子
	.back_view {
		// 返回按钮
		.back_btn {
		}
		// 返回按钮-悬浮
		.back_btn:hover {
		}
	}
	.bread_view {
		:deep(.breadcrumb) {
			.el-breadcrumb__separator {
			}
			.first_breadcrumb {
				.el-breadcrumb__inner {
				}
			}
			.second_breadcrumb {
				.el-breadcrumb__inner {
				}
			}
		}
	}
	// 分类盒子
	.category_view {
		// 分类item
		.category {
		}
		// item-悬浮
		.category:hover {
		}
		// item-选中
		.categoryActive {
		}
	}

	//搜索
	.list_search {
		.search_view {
			.search_label {
			}
			.search_box {
				// 输入框
				:deep(.search_inp) {
					.is-focus {
						box-shadow: none !important;
					}
				}
			}
		}
		.search_btn_view {
			// 搜索按钮
			.search_btn {
			}
			// 搜索按钮-悬浮
			.search_btn:hover {
			}
			// 新增按钮
			.add_btn {
			}
			// 新增按钮-悬浮
			.add_btn:hover {
			}
		}
	}

	// 数据盒子
	.page_list {
		//列表
		.data_box {
			.data_view {
				// 表格样式
				.el-table {
					padding: 0;
					background: #fff;
					width: 100%;
					border-color: #eee;
					border-width: 1px 0 0 1px;
					border-style: solid;
					:deep(.el-table__header-wrapper) {
						thead {
							width: 100%;
							tr {
								background: #fff;
								th {
									padding: 10px 0;
									border-color: #eee;
									border-width: 0 1px 1px 0;
									border-style: solid;
									text-align: left;
									.cell {
										padding: 0 10px;
										word-wrap: normal;
										color: #666;
										white-space: normal;
										font-weight: bold;
										display: inline-block;
										vertical-align: middle;
										font-size: 15px;
										line-height: 24px;
										text-overflow: ellipsis;
										word-break: break-all;
										width: 100%;
										position: relative;
										//未选中样式
										.el-checkbox {
											//复选框
											.el-checkbox__inner {
												background: #fff;
												border-color: #999;
											}
										}
										//选中样式
										.is-checked {
											//复选框
											.el-checkbox__inner {
												background: #55ffff;
												border-color: #55ffff;
											}
										}
									}
								}
							}
						}
					}
					:deep(.el-table__body-wrapper) {
						tbody {
							width: 100%;
							tr {
								background: #fff;
								td {
									padding: 10px 0 0;
									color: #666;
									background: #fff;
									border-color: #eee;
									border-width: 0 1px 1px 0;
									border-style: solid;
									text-align: left;
									.cell {
										padding: 0 10px;
										overflow: hidden;
										word-break: break-all;
										white-space: normal;
										line-height: 24px;
										text-overflow: ellipsis;
										//未选中样式
										.el-checkbox {
											//复选框
											.el-checkbox__inner {
												background: #fff;
												border-color: #999;
											}
										}
										//选中样式
										.is-checked {
											//复选框
											.el-checkbox__inner {
												background: #55ffff;
												border-color: #55ffff;
											}
										}
									}
								}
							}
							tr.el-table__row--striped {
								td {
									background: #FAFAFA !important;
								}
							}
							tr:hover {
								td {
									padding: 10px 0 0;
									color: #333;
									background: #f6f6f6;
									border-color: #eee;
									border-width: 0 1px 1px 0;
									border-style: solid;
									text-align: left;
								}
							}
						}
					}
				}
			}
		}
	}

	// 分页器
	.el-pagination {
		// 总页码
		:deep(.el-pagination__total) {
		}
		// 上一页
		:deep(.btn-prev) {
		}
		// 下一页
		:deep(.btn-next) {
		}
		// 上一页禁用
		:deep(.btn-prev:disabled) {
		}
		// 下一页禁用
		:deep(.btn-next:disabled) {
		}
		// 页码
		:deep(.el-pager) {
			// 数字
			.number {
			}
			// 数字悬浮
			.number:hover {
			}
			// 选中
			.number.is-active {
			}
		}
		// sizes
		:deep(.el-pagination__sizes) {
			.el-select {
				//去掉默认样式
				.select-trigger{
					height: 100%;
					.el-input{
						height: 100%;
						.is-focus {
							box-shadow: none !important;
						}
					}
				}
			}
		}
		// 跳页
		:deep(.el-pagination__jump) {
			// 输入框
			.el-input {
				.is-focus {
					box-shadow: none !important;
				}
			}
		}
	}
	
	// 热门信息盒子
	.hot_view {
		// 标题
		.hot_title {
		}

		.hot_list {
			// item
			.hot {
				//图片盒子
				.hot_img_view {
					// 图片
					.hot_img {
					}
				}
				// 内容盒子
				.hot_content {
					// 名称
					.hot_text {
					}
				}
			}
		}
	}
</style>
